package com.markerhub.controller;

import com.huaban.analysis.jieba.JiebaSegmenter;
import com.markerhub.common.lang.Result;
import com.markerhub.entity.GoodsComment;
import com.markerhub.entity.SysUser;
import com.markerhub.service.GoodsCommentService;
import com.markerhub.service.SysDictValueService;
import com.markerhub.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.Date;
import java.util.List;

/**
 * @author jsx on 2023/2/19
 **/
@RestController
@RequestMapping("/goods/comment")
public class GoodsCommentController extends BaseController {

    @Autowired
    private GoodsCommentService sysGoodsCommentService;
    @Autowired
    private SysDictValueService sysDictValueService;

    //增加一条记录
    @PostMapping("/save")
    public Result save(@RequestBody GoodsComment goodsComment, Principal principal){
        //判断redis中是否已经禁言该用户
        SysUser user = sysUserService.getByUsername(principal.getName());
        Object flag = redisUtil.get(user.getId().toString());
        if(flag != null){
            //被禁言
            return Result.fail("对不起你已经被禁言!");
        }
        //判断是否含有不良信息
        //分词，结巴库
        JiebaSegmenter segmenter = new JiebaSegmenter();
        List<String> content = segmenter.sentenceProcess(goodsComment.getContent());
        //查询字典值，判断是否存在result在这个不良信息表中
        boolean noHealthyInfo = sysDictValueService.isNoHealthyInfo(content);
        if(noHealthyInfo){
            goodsComment.setCreater(user.getId().toString());
            goodsComment.setCreate_time(DateUtils.getTime(new Date()));
            sysGoodsCommentService.save(goodsComment);
            return Result.succ("评论成功");
        }else{
            redisUtil.set(user.getId().toString(),"123456",60*5);
            return Result.fail("你含有不良信息，将被禁言5分钟");
        }

    }

    //返回评论参数
    @GetMapping("/info/{goodId}")
    public Result info(@PathVariable("goodId") String goodId){
        //查询所有的关评论
        List<GoodsComment> goodsComments = sysGoodsCommentService.selectByGoodsInfo(goodId);
        for (GoodsComment goodsComment : goodsComments) {
            goodsComment.setCreate_time(goodsComment.getCreateTime());
        }
        return Result.succ(goodsComments);
    }

}
